#!/usr/bin/env python
# encoding: utf-8

import sys
import time
import logging
import config
import re

from lib.JobQ import JobQueue
from lib.utils import ConfigSectionMap
from multiprocessing.dummy import DummyProcess
from lib.app_mysql import appMysql as db

reload(sys)
sys.setdefaultencoding("utf-8")

log = logging.getLogger("")


class alert_consumer(DummyProcess):
    def __init__(self):
        DummyProcess.__init__(self)
        log.info("启动消费worker, 消费报警信息.....")
        self.daemon = True
        self.config = ConfigSectionMap("GLOBAL")
        self.start()

    def run(self):
        while True:
            try:
                Consumer = JobQueue(self.config.get("alert_queue"))
                Consumer.connection()
                Consumer.consumer(ExplainAlert, consumer_tag="explain")
            except Exception as e:
                Consumer.close()
                time.sleep(3)


class ExplainAlert(object):
    def __init__(self, ch, method, properties, body):
        self.config = ConfigSectionMap("GLOBAL")
        self.ch = ch
        self.method = method
        self.properties = properties
        self.body = eval(body)
        self.main()

    def main(self):
        self.save_msg_to_mysql()

        log.info("此处获取到的config为: {0}".format(config.config))
        info = list()
        rules = config.config.get("rules")
        for r in rules:
            if r.get("match_field") == "title":
                obj = re.compile(r.get("regex"))

                if obj.findall(self.body.get("title")):
                    log.info("match success")
                    msg = dict(host=self.body.get("target"), script=r.get("action"))
                    info.append(msg)

            elif r.get("match_field") == 'content':
                obj = re.compile(r.get("regex"))
                if obj.findall(self.body.get("content")):
                    log.info("match success")
                    msg = dict(host=self.body.get("target"), script=r.get("action"))
                    info.append(msg)

        try:
            sender = JobQueue(self.config.get("salt_queue"))
            sender.connection()
            sender.put(info)
            self.ack_mesg()
        except Exception as e:
            log.error("push message to Q failed....reason: {0}".format(e))
            self.cancer_mesg()

    def save_msg_to_mysql(self):
        fields = []
        values = []
        for k, v in self.body.iteritems():
            fields.append(k)
            values.append(v)

        fields.append("updateTime")
        values.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        sql = "insert into alert({0}) values{1}".format(",".join(fields), tuple(values))
        db.autocommit(True)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
        except Exception as e:
            log.error("Save alert msg failed... reason: {e}".format(e=e))
        finally:
            cursor.close()

    def ack_mesg(self):
        self.ch.basic_ack(delivery_tag=self.method.delivery_tag)

    def cancer_mesg(self):
        self.ch.basic_cancel(consumer_tag='explain')
        self.ch.stop_sonsuming()